<?php

namespace app\back\controller;
use think\Cache;
use \think\Controller;
use app\back\model\Category;
use app\back\validate\CategoryValidate;
use think\Db;
use think\Exception;


class CategoryController extends Controller
{
    const CACHE_TYPE_KEY = "cache_key";


    //添加修改商品
    public function setAction()
    {
        $req = request();

        if($req->isGet()){
            $m = session("message");
            $i = session("info");
            $id =input("id");
            $model = new Category();

            $one = Category::get($id);
            if(!(isset($m)&&isset($i))){
                $message = "";
                $info =$one;
            }
            else{
                $message = $m;
                $info =$i;
            }

            $this->assign("category_list",$model->getTree());

            $this->assign("msg",$message);
            $this->assign("info",$info);
            $this->assign("id",$id);
            return $this->fetch();
        }
        elseif ($req->isPost()){
            $model = new Category;
            $v = new  CategoryValidate;
            $data = input("post.");

            if(!$v->batch(true)->check($data)){
                return $this->redirect("set",[],202,[
                    "message"=>$v->getError(),
                    "info" => $data
                ]);
            }
            $result = null;
            if(!empty($data["id"])){
                $one = $model->find($data["id"]);
                $result = $one->save($data);
            }
            else{
                $result = $model->save($data);
            }
            if(!$result){
                return "添加失败：".$this->error();
            }
            else{
                return $this->redirect("index");
            }


        }
        else{


        }

    }


    //筛选
    public function indexAction()
    {
        $m = new Category();
           if(!($list=Cache::get(self::CACHE_TYPE_KEY))){
               $list = $m->getTree();
               Cache::set(self::CACHE_TYPE_KEY,$list);
           }



        $this->assign("list",$list);
        return $this->fetch();
    }




    //删除

    public function multiAction()
    {
        $data = input("selected/a");
        if(count($data)==0) $this->redirect("index");

        Category::destroy($data);
        $this->redirect("index");
    }




}





